package com.hihonor.excel;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.hihonor.Main;

import javax.swing.table.DefaultTableModel;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * @author 李志雄
 * @since 2023-10-14
 */
public class ExcelUtil {
    private ExcelUtil() {
    }

    public static void export(String savePath, Main main) {
        List<List<String>> headList = new ArrayList<>();
        for (int idx = 0; idx < main.getTableColumn().length; idx++) {
            headList.add(ListUtil.list(false, main.getTableColumn()[idx]));
        }
        String fileName = "刷卡记录_" + DateUtil.format(DateTime.now(), "yyyyMMddHHmmss") + ".xlsx";
        File file = FileUtil.file(savePath, fileName);
        EasyExcelFactory.write(file).head(headList).registerWriteHandler(new SimpleColumnWidthStyleStrategy(20)).sheet("Sheet").doWrite(getWriteData(main));
    }

    private static List<List<String>> getWriteData(Main main) {
        List<List<String>> list = new ArrayList<>();
        DefaultTableModel tableModel = main.getDefaultTableModel();
        Vector<Vector> vector = tableModel.getDataVector();
        for (Vector value : vector) {
            List<String> record = new ArrayList<>();
            Vector rowVector = value;
            for (int idx = 0; idx < main.getTableColumn().length; idx++) {
                record.add(rowVector.get(idx).toString());
            }
            list.add(record);
        }
        return list;
    }
}
